package com.xs.ahoi.hcxs.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import butterknife.*;
import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.dao.BookDao;
import com.xs.ahoi.hcxs.dao.BookMarkDao;
import com.xs.ahoi.hcxs.model.Book;
import com.xs.ahoi.hcxs.model.BookMark;
import com.xs.ahoi.hcxs.ui.dialog.DialogCommonDelete;
import com.xs.ahoi.hcxs.utils.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * author: ahoi
 * date: 2018/6/27 17:24
 * description: 书签
 */
public class BookMarkFragment extends Fragment {

    @BindView(R.id.lvBookMark)
    public ListView lvBookMark;

    // 文件目录名集合
    private Book book;
    // 书籍ID
    private int bookId;
    // 书总长度
    private long totalLenth;
    private BookMarkFragAdapter adapter;
    private List<BookMark> bookMarks;
    private List<Map<String, Object>> datas;
    private BookMarkDao bookMarkDao;
    private BookDao bookDao;
    private FragmentActivity context;
    // 用于ButterKnife解绑
    private Unbinder unbinder;
    private Callback listener;
    // 长按项的下标
    private int longClickIndex = 0;

    // 删除弹出框
    private DialogCommonDelete dialogCommonDelete;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bookmark, container, false);
        unbinder = ButterKnife.bind(this, view);
        context = getActivity();
        init();
        initListener();
        return view;
    }

    private void init() {
        bookMarkDao = BookMarkDao.getInstance();
        bookDao = BookDao.getInstance();

        // 初始化删除提示框
        dialogCommonDelete = new DialogCommonDelete(getContext());

        // 获取书籍
        bookId = getArguments().getInt(Constants.BOOK_ID);
        book = bookDao.getById(bookId);
        totalLenth = book.getTotalLenth();

        // 更新视图
        updateView();
    }

    // 更新视图
    private void updateView() {

        // 查询本书所有书签
        bookMarks = bookMarkDao.listAll(bookId);

        // 组装datas数据
        datas = new ArrayList<>();
        Map<String, Object> map;
        for (BookMark mark : bookMarks) {
            map = MapUtil.build()
                    .put("title", mark.getCatalog())
                    .put("content", "        " + mark.getContent() + "...")
                    .put("createTime", "时间：" + DateUtil.long2String(mark.getCreateTime(), DateUtil.FORMAT_YMD_HM))
                    .put("percent", "进度：" + StringUtils.getPercent(mark.getPosition(), totalLenth))
                    .over();
            datas.add(map);
        }

        // 绑定adapter
        String[] keys = {"title", "content", "createTime", "percent"};
        int[] res = {R.id.tvTitle, R.id.tvContent, R.id.tvCreateTime, R.id.tvPosition};
        adapter = new BookMarkFragAdapter(context, datas, R.layout.listview_item_bookmark, keys, res);
        lvBookMark.setAdapter(adapter);
    }

    private void initListener() {
        dialogCommonDelete.setDeleteListener((isDeleteLocal) -> {
            // 删除书签
            int id = bookMarks.get(longClickIndex).getId();
            bookMarkDao.deleteById(id);
            ToastUtil.show("已删除");

            // 更新视图
            bookMarks.remove(longClickIndex);
            datas.remove(longClickIndex);
            adapter.notifyDataSetChanged();
        });
    }

    @OnItemClick({R.id.lvBookMark})
    public void onItemClick(int position) {
        // 返回到内容页面的指定下标位置
        BookMark bookMark = bookMarks.get(position);
        listener.back(bookMark.getPosition());
    }

    @OnItemLongClick({R.id.lvBookMark})
    public boolean onItemLongClick(int position) {
        longClickIndex = position;
        dialogCommonDelete.show();
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnifeUtil.unbind(unbinder);
    }

    // 自定义SimpleAdapter
    private class BookMarkFragAdapter extends SimpleAdapter {

        private BookMarkFragAdapter(Context context, List<? extends Map<String, Object>> datas, int resource, String[] from, int[] to) {
            super(context, datas, resource, from, to);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return super.getView(position, convertView, parent);
        }

        @Override
        public Map<String, Object> getItem(int position) {
            return datas.get(position);
        }
    }

    public void setListener(Callback listener) {
        this.listener = listener;
    }

    public interface Callback {
        void back(int position);
    }
}
